<template>
    <div>
        <avue-crud v-if="option.column" :page.sync="page" :data="data.data" :option="option" @row-save="save"
            @row-update="update" @row-del="reomve" @on-load="changePage" @sort-change="changeSort">
        </avue-crud>
    </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';

@Component
export default class ResourceList extends Vue {
    @Prop(String) resource!: string
    data: any = {}
    option: any = {}
    page: any = {
        pageSize: 5,
        pageSizes: [2, 5, 10],
        total: 0
    }
    query: any = {
        limit: 2
    }

    async fetchOption() {
        const res = await this.$http.get(`${this.resource}/option`)
        this.option = res.data
    }

    //@ts-ignore
    async changePage({ pageSize, currentPage }) {
        this.query.limit = pageSize
        this.query.page = currentPage
        this.fetch()
    }

    //@ts-ignore
    async changeSort({ prop, order }) {
        if (!order) {
            this.query.sort = null
        } else {
            this.query.sort = {
                [prop]: order === 'ascending' ? 1 : -1
            }
        }
        this.fetch()
    }

    async fetch() {
        const res = await this.$http.get(`${this.resource}`, {
            params: {
                query: this.query
            }
        })
        this.data = res.data
        this.page.total = res.data.total
    }

    async save(row: any, done: Function) {
        await this.$http.post(`${this.resource}`, row)
        this.$message.success('添加成功')
        this.fetch()
        done()
    }

    async update(row: { _id: string; }, index: number, done: Function) {
        await this.$http.put(`${this.resource}/${row._id}`, row)
        this.$message.success('更新成功')
        this.fetch()
        done()
    }

    async reomve(row: any) {
        try {
            await this.$confirm('是否确认删除？')
        } catch (error) {
            return
        }
        await this.$http.delete(`${this.resource}/${row._id}`)
        this.$message.success('删除成功！')
        this.fetch()
    }

    created() {
        this.fetchOption()
        this.fetch()
    }
}
</script>

<style scoped>
</style>